<template>
  <div class="crm-page customer-add-page">
    <div class="page-header">{{ title }}合同</div>
    <div class="page-content transparent">
      <div class="page-card">
        <div class="card-title">
          <el-button class="back-btn" size="medium" type="text" icon="el-icon-back" @click="goMainBack()">返回</el-button>
        </div>
        <el-form ref="form" :model="form" label-width="120px" :rules="rules">
          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              基本信息
            </div>
            <div class="card-item">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="合同编号" prop="number">
                    <el-input v-model="form.number" placeholder="请输入合同编号" maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="合同名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入报价单名称" maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户名" prop="customerId">
                    <VbSelect v-model="form.customerId" placeholder="请选择客户名" :name="form.customerName" style="width:100%" :load-data="loadCustomerData" @change="changeCustomer" />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="所有人" prop="owner">
                    <el-input v-model="form.owner" placeholder="" maxlength="50" disabled readonly />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="报价单号" prop="quoteId">
                    <VbSelect v-model="form.quoteId" placeholder="请选择报价单号" :name="form.quoteNo" style="width:100%" :load-data="loadQuoteData" @change="changeQuote" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="金额（元）" prop="amount">
                    <el-input v-model="form.amount" v-checkMoney placeholder="请输入合同金额" maxlength="13" />
                  </el-form-item>
                </el-col>
                <!-- <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="合同状态" prop="status">
                    <el-select v-model="form.status" disabled style="width:100%">
                      <el-option v-for="cs in contractStatus" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="付款方式" prop="paymentMode">
                    <el-select v-model="form.paymentMode" style="width:100%">
                      <el-option v-for="cs in payMethods" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="币种" prop="currency">
                    <el-select v-model="form.currency" style="width:100%">
                      <el-option v-for="cs in currencys" :key="cs.value" :value="cs.value" :label="cs.label" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="开始日期" prop="startDate">
                    <el-date-picker
                      v-model="form.startDate"
                      style="width:100%"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="结束日期" prop="endDate">
                    <el-date-picker
                      v-model="form.endDate"
                      style="width:100%"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="汇率" prop="rate">
                    <el-input v-model="form.rate" v-checkMoney placeholder="请输入汇率" maxlength="11" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="税率(%)" prop="taxRate">
                    <el-input v-model="form.taxRate" v-checkMoney placeholder="请输入税率" maxlength="5" />
                  </el-form-item>
                </el-col>

              </el-row>
            </div>
          </div>
          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              地址信息
            </div>
            <div class="card-item">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                  <el-form-item prop="invoiceList" label="开票地址">
                    <VbAreasForm v-model="form.invoiceList" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                  <el-form-item prop="receiveList" label="收货地址">
                    <VbAreasForm v-model="form.receiveList" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="page-card-content">
            <div class="card-item">
              <el-form-item prop="specialTerms" label="特别条款">
                <el-input v-model="form.specialTerms" type="textarea" :rows="6" maxlength="500" placeholder="请输入条款" />
              </el-form-item>
              <el-form-item style="padding-top:20px" prop="remark" label="备注">
                <el-input v-model="form.remark" type="textarea" :rows="6" maxlength="255" placeholder="请输入备注" />
              </el-form-item>
            </div>
          </div>
          <div class="page-card-content">
            <div class="item-title" style="margin-top:20px">
              签字信息
            </div>
            <div class="card-item">
              <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户签字人" prop="customerSignatory">
                    <el-input v-model="form.customerSignatory" placeholder="请输入客户签字人" maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="公司签字人" prop="companySignatory">
                    <el-input v-model="form.companySignatory" placeholder="请输入公司签字人" maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="签字人职务" prop="signatoryPosition">
                    <el-input v-model="form.signatoryPosition" placeholder="请输入职务" maxlength="50" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item style="height:43px" />
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="客户签字日期" prop="customerSignDate">
                    <el-date-picker
                      v-model="form.customerSignDate"
                      style="width:100%"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
                  <el-form-item label="公司签字日期" prop="companySignDate">
                    <el-date-picker
                      v-model="form.companySignDate"
                      style="width:100%"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                  <el-form-item label="附件" prop="no" style="width:500px">
                    <VbUpload v-model="form.fileList" :max="20" multiple accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/pdf,image/jpeg,image/png" :limit="5">
                      <div slot="tip" class="el-upload__tip"> 1.支持格式：PDF、docx、doc、xls、xlsx、PNG、JPG、JPEG；<br> 2.最多可上传5个文件，每个文件不超过20M</div>
                    </VbUpload>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="page-card-content" style="padding-top:20px">
            <el-row style="text-align:right">
              <el-button plain @click="handleClose">取消</el-button>
              <el-button type="primary" @click="submitForm">保存</el-button>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import VbAreasForm from '@/components/VbAreasForm'
import VbUpload from '@/components/VbUpload'

import { getCustomerSelect, getCustomer } from '@/api/customer'
import { getQuoteSelect, getQuote } from '@/api/quote'

import { getContract, saveContract, updateContract } from '@/api/contract'

import { contractStatus, payMethods, currencys } from '@/utils/enums'
import { formatTime } from '@/utils/tools'
import BigNumber from 'bignumber.js'
export default {
  name: 'CustomerAdd',
  components: { VbAreasForm, VbUpload },
  data() {
    const validateAddress = (rule, value, callback) => {
      let pass = true
      console.log('validateAddress:', value)
      if (value && value.length > 0) {
        value.forEach(item => {
          if ((item.areas && item.areas.length !== 3) || !item.address) {
            pass = false
          }
        })
        if (!pass) {
          callback(new Error('地址不能有空'))
        } else {
          callback()
        }
      } else {
        callback(new Error('地址不能有空'))
      }
    }
    return {
      contractStatus,
      currencys,
      payMethods,
      billList: [],
      receiveList: [],
      form: {
        'amount': '',
        'businessId': '',
        'companySignDate': this.getDatetime(),
        'companySignatory': '',
        'currency': 'rmb',
        'customerId': '',
        'customerSignDate': this.getDatetime(),
        'customerSignatory': '',
        'endDate': this.getDatetime(),
        'fileList': [],
        'invoiceList': [],
        'name': '',
        'paymentMode': 2,
        'rate': '1',
        'receiveList': [],
        'remark': '',
        'signatoryPosition': '',
        'specialTerms': '',
        'startDate': this.getDatetime(),
        'status': 1,
        owner: '',
        taxRate: ''

      },
      rules: {
        number: [
          {
            required: true, message: '合同编号不能为空', trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '报价单名称不能为空', trigger: 'blur' }
        ],
        customerId: [
          { required: true, message: '客户名不能为空', trigger: 'blur' }
        ],
        endDate: [
          { required: true, message: '结束日期不能为空', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '开始日期不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '金额不能为空', trigger: 'blur' }
        ],
        invoiceList: [
          { validator: validateAddress, trigger: 'blur' }
        ],
        receiveList: [
          { validator: validateAddress, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '修改' : '新增'
    }
  },
  mounted() {
    const id = this.$route.query.id
    if (id) {
      getContract({ id }).then(res => {
        if (!res.fileList) {
          res.fileList = []
        }
        this.form = res
      })
    } else {
      this.form.owner = this.USER.userName
      const customerId = this.$route.query.customerId
      const customerName = this.$route.query.customerName
      if (customerId && customerName) {
        this.form.customerId = customerId
        this.form.customerName = customerName
        this.changeCustomer({ id: customerId })
      }
      const quoteId = this.$route.query.quoteId
      const quoteNo = this.$route.query.quoteNo
      if (quoteId && quoteNo) {
        this.form.quoteId = quoteId
        this.form.quoteNo = quoteNo
        this.changeQuote({ id: quoteId })
      }
    }
  },
  methods: {
    formatTime,
    getDatetime() {
      const date = new Date()
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + ' '
      return Y + M + D
    },
    loadCustomerData(params) {
      return getCustomerSelect(params).then(res => {
        return res
      })
    },
    loadQuoteData(params) {
      return getQuoteSelect(params).then(res => {
        return res
      })
    },
    changeCustomer(v) {
      // 获取客户的地址
      getCustomer({ id: v.id }).then(res => {
        this.form.receiveList = res.receiveList || []
        this.form.invoiceList = res.invoiceList || []
      })
    },
    changeQuote(v) {
      console.log(v)
      getQuote({ id: v.id }).then(res => {
        this.form.amount = new BigNumber(res.amount || 0).toFixed(2)
        this.form.currency = res.currency
        this.form.rate = res.rate
      })
    },
    handleClose() {
      this.$router.back()
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 有id 是修改
          // 处理地址
          if (this.form.invoiceList) {
            this.form.invoiceList.forEach(item => {
              item.province = item.areas[0]
              item.city = item.areas[1]
              item.county = item.areas[2]
            })
          }
          if (this.form.receiveList) {
            this.form.receiveList.forEach(item => {
              item.province = item.areas[0]
              item.city = item.areas[1]
              item.county = item.areas[2]
            })
          }
          if (this.form.id) {
            updateContract(this.form).then(res => {
              console.log('updateQuote:', res)
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.$router.back(-1)
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '修改失败'
              })
            })
          } else {
            saveContract(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功'
              })
              this.$router.back(-1)
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '新增失败'
              })
            })
          }
        }
      })
    }

  }
}
</script>
<style lang="scss">
.customer-add-page{
    .el-form-item--small.el-form-item{
      margin-bottom: 0;
    }
    .num-input.el-input--small .el-input__inner{
      text-align: right;
    }

}

</style>

